package com.zzy.demo.service.mqtt;

import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.springframework.stereotype.Component;
import lombok.extern.slf4j.Slf4j;

/**
 * MQTT回调函数
 *
 * @author Mr.Qu
 * @since 2020/11/18
 */
@Slf4j
@Component
public class EventCallback implements MqttCallback {

	/**
	 * MQTT 断开连接会执行此方法
	 */
	@Override
	public void connectionLost(Throwable cause) {
		log.error(cause.getMessage(), cause);
	}

	/**
	 * publish发布成功后会执行到这里
	 */
	@Override
	public void deliveryComplete(IMqttDeliveryToken token) {
		try {
			System.out.println("--------发布成功--------" + new String(token.getMessage().getPayload()));
		} catch (MqttException e) {
			e.printStackTrace();
		}
	}

	/**
	 * subscribe订阅后得到的消息会执行到这里
	 */
	@Override
	public void messageArrived(String topic, MqttMessage message) {
		log.info("[{}] : {}", topic, new String(message.getPayload()));
		
	}
}
